package com.zbxx.servlet;


import com.google.gson.Gson;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class searchServlet extends HttpServlet {
    static List<String> datas = new ArrayList<String>();

    static {
        datas.add("java框架");
        datas.add("java基础");
        datas.add("java项目");
        datas.add("c语言");
        datas.add("c语言视频");
        datas.add("php视频");
        datas.add("php项目");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //首先获得从客户端发送来的数据keyword
        String keyword = request.getParameter("keyword");
        //获得关键字之后进行处理，得到关联数据
        List<String> listData=getData(keyword);
        System.out.println(listData);
        //返回json格式
        Gson gson=new Gson();
        String json=gson.toJson(listData);
        System.out.println(gson.toJson(listData));
        response.getWriter().write(gson.toJson(listData).toString());
    }

    //获得关联数据的方法
    public List<String> getData(String keyword) {
        List<String> list = new ArrayList<String>();
        for (String data:datas){
            if(data.contains(keyword)){
                 list.add(data);
            }
        }
            return list;
    }
}
